package com.wwcom.darteagle.view;

import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.PathShape;
import android.text.Html;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.wwcom.darteagle.R;
import com.wwcom.darteagle.model.GlobalAppData;
import com.wwcom.darteagle.model.Match;
import com.wwcom.darteagle.model.MatchPlayer;
import com.wwcom.darteagle.model.VisitScore;
import com.wwcom.darteagle.util.Settings;

public class ScoreMatrixView extends LinearLayout {
	private static final int NUM_PLAYERS_BEFORE_SCROLL_PORTRAIT= 4;
	private static final int NUM_PLAYERS_BEFORE_SCROLL_LANDSCAPE= 2;
	
	//private data
	private Context context;
	private Match match;
	private PlayerScoreArrayAdapter playerScoreAdaptor;
	private boolean showAverages;
	private int themeId;
	private float dpiScale;
	private boolean isLandscape;
	
	//constructors
	public ScoreMatrixView(Context context) {
		super(context);
		initialiseSelf(context);
	}

	public ScoreMatrixView(Context context, AttributeSet attrs) {
		super(context,attrs);
		initialiseSelf(context);
	}
	
	private void initialiseSelf(Context context) {
    	View.inflate(context, R.layout.score_matrix, this);

    	this.context= context;
    	themeId= Settings.getThemeID(context);

        DisplayMetrics metrics = new DisplayMetrics();
        ((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(metrics);
        dpiScale= metrics.density;
        
        isLandscape= context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; 
    	
		GlobalAppData gd= GlobalAppData.getSingletonInstance();
		this.match= gd.match;
    	ListView viewList= (ListView) this.findViewById(R.id.score_matrix_list);
    	playerScoreAdaptor = new PlayerScoreArrayAdapter(context,match.getPlayerCurrentScores());
    	viewList.setAdapter(playerScoreAdaptor);
    	viewList.setDividerHeight(0);
    	String matchSubStr;
    	if (match.getNumSets() > 0)
    		matchSubStr= context.getString(R.string.scorematrix_first_to_sets,match.getNumSets());
    	else
    		matchSubStr= context.getString(R.string.scorematrix_first_to_legs,match.getNumLegs());
    	viewList.setFocusable(false);
    	//set max height of the list view if we have loads of players
    	if (!isLandscape && match.getMatchPlayers().size() > NUM_PLAYERS_BEFORE_SCROLL_PORTRAIT) {
    		ViewGroup.LayoutParams lp2 = viewList.getLayoutParams();
    		lp2.height= 200;
    		viewList.setLayoutParams(lp2);
    	}
		if (themeId == R.style.Theme_SKY || themeId == R.style.Theme_SKYWC2012)
			matchSubStr= matchSubStr.toUpperCase();
    	((TextView)this.findViewById(R.id.matchTitle)).setText(matchSubStr);
        	    
    	boolean useSets= match.getNumSets()>0;
    	if (!useSets) {
    		TextView setsTitle= ((TextView)this.findViewById(R.id.setsTitle)); 
    		setsTitle.setText("");
    		ViewGroup.LayoutParams lp = setsTitle.getLayoutParams();
    		lp.width= 0;
    		setsTitle.setLayoutParams(lp);
    	}
    	showAverages= false;
    	if (themeId == R.style.Theme_BBC) {
        	if (useSets)
        		((TextView)this.findViewById(R.id.setsTitle)).setText(context.getString(R.string.scorematrix_sets_bbc));    		
        	((TextView)this.findViewById(R.id.legsTitle)).setText(context.getString(R.string.scorematrix_legs_bbc));    		
        	((TextView)this.findViewById(R.id.ptsTitle)).setText(context.getString(R.string.scorematrix_pts_bbc));    		
    	} else if (themeId == R.style.Theme_SKY || themeId == R.style.Theme_SKYWC2012) {
        	if (useSets)
        		((TextView)this.findViewById(R.id.setsTitle)).setText(context.getString(R.string.scorematrix_sets_sky));    		
        	((TextView)this.findViewById(R.id.legsTitle)).setText(context.getString(R.string.scorematrix_legs_sky));    		
        	((TextView)this.findViewById(R.id.ptsTitle)).setText(context.getString(R.string.scorematrix_pts_sky));    		    		
    	}
	}

	
	public void newLeg() {
    	ListView viewList= (ListView) this.findViewById(R.id.score_matrix_list);
    	playerScoreAdaptor = new PlayerScoreArrayAdapter(context,match.getPlayerCurrentScores());
    	viewList.setAdapter(playerScoreAdaptor);		
	}
	
	public void updateView() {
		playerScoreAdaptor.notifyDataSetChanged();
		setDisplayVars();		
    	if ((!isLandscape && match.getMatchPlayers().size() > NUM_PLAYERS_BEFORE_SCROLL_PORTRAIT) ||
    			(isLandscape && match.getMatchPlayers().size() > NUM_PLAYERS_BEFORE_SCROLL_LANDSCAPE)) {
    		int playerInd= match.getMatchPlayers().indexOf(match.getCurrentPlayer());
        	ListView viewList= (ListView) this.findViewById(R.id.score_matrix_list);
    		viewList.smoothScrollToPosition(playerInd);
    	}
	}
	        
    //private classes
	private static class PlayerScoreViewHolder {
		protected TextView playerName;
		protected TextView playerSets;
		protected TextView playerLegs;
		protected TextView playerNumDarts;
		protected TextView playerPoints;
		protected TextView playerMarker;
		protected TextView playerMarkerAlt;
		protected TextView playerInfoString;
		protected TextView playerInfoStringSpacer1;
		protected TextView playerInfoStringSpacer2;
		protected TextView player9Dart;
	}

	private class PlayerScoreArrayAdapter extends ArrayAdapter<VisitScore> {
    	private final List<VisitScore> list;
    	private final Context context;

    	public PlayerScoreArrayAdapter(Context context, List<VisitScore> list) {
    		super(context, R.layout.score_matrix_row, list);
    		this.context = context;
    		this.list = list;
    	}

    	@Override
    	public View getView(int position, View convertView, ViewGroup parent) {
    		View view = null;
    		if (convertView == null) {
    			LayoutInflater inflator = ((Activity) context).getLayoutInflater();
    			view = inflator.inflate(R.layout.score_matrix_row, null);
    			final PlayerScoreViewHolder viewHolder = new PlayerScoreViewHolder();
    			viewHolder.playerName = (TextView) view.findViewById(R.id.playerName);
    			viewHolder.playerPoints = (TextView) view.findViewById(R.id.playerPoints);
    			viewHolder.playerLegs = (TextView) view.findViewById(R.id.playerLegs);
    			viewHolder.playerSets = (TextView) view.findViewById(R.id.playerSets);
    			if (match.getNumSets() == 0) {
    	    		ViewGroup.LayoutParams lp = viewHolder.playerSets.getLayoutParams();
    	    		lp.width= 0;
    	    		viewHolder.playerSets.setLayoutParams(lp);
    			}
    			viewHolder.playerNumDarts = (TextView) view.findViewById(R.id.playerNumDarts);
    			viewHolder.playerMarker = (TextView) view.findViewById(R.id.playerMarker);
    			viewHolder.playerMarkerAlt = (TextView) view.findViewById(R.id.playerMarkerAlt);
    			viewHolder.playerInfoString = (TextView) view.findViewById(R.id.playerInfoString);
   				viewHolder.playerInfoStringSpacer1 = (TextView) view.findViewById(R.id.playerInfoSpacer1);
   				viewHolder.playerInfoStringSpacer2 = (TextView) view.findViewById(R.id.playerInfoSpacer2);
    			viewHolder.player9Dart = (TextView) view.findViewById(R.id.player9Dart);
    			view.setTag(viewHolder);
    		} else {
    			view = convertView;
    		}
    		VisitScore vs= list.get(position);
    		MatchPlayer mp= vs.getMatchPlayer();
    		PlayerScoreViewHolder holder = (PlayerScoreViewHolder) view.getTag();
    		holder.playerName.setText(mp.getPlayer().getName().toUpperCase());
        	if (themeId == R.style.Theme_BBC) {
        		if (match.isCurrentPlayer(vs.getMatchPlayer())) {
	    			holder.playerName.setTextColor(Color.parseColor("#FFFFFF"));
	    		} else {
	    			holder.playerName.setTextColor(Color.parseColor("#888888"));
	    		}
    			holder.playerName.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);    			
        	} else if (themeId == R.style.Theme_SKY) {
        		if (match.isLegStartPlayer(vs.getMatchPlayer())) {
        			if (isLandscape) {
        				Drawable img = getContext().getResources().getDrawable( R.drawable.player_marker_sky_large );        				
        				holder.playerName.setCompoundDrawablesWithIntrinsicBounds(null,null,img,null);
        			} else {
        				Drawable img = getContext().getResources().getDrawable( R.drawable.player_marker_sky );
        				holder.playerName.setCompoundDrawablesWithIntrinsicBounds(null,null,img,null);
        			}
        		} else {
        			holder.playerName.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);    			
        		}
        	} else if (themeId == R.style.Theme_SKYWC2012) {
        		if (match.isLegStartPlayer(vs.getMatchPlayer())) {
        			if (isLandscape) {
        				Drawable img = getContext().getResources().getDrawable( R.drawable.player_marker_wc2012_sky_large );
        				holder.playerName.setCompoundDrawablesWithIntrinsicBounds(null,null,img,null);
        			} else {
        				Drawable img = getContext().getResources().getDrawable( R.drawable.player_marker_wc2012_sky );
        				holder.playerName.setCompoundDrawablesWithIntrinsicBounds(null,null,img,null);        				
        			}
        		} else {
        			holder.playerName.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);    			
        		}
        	}
    		holder.playerPoints.setText(Integer.toString(vs.getLegScore()));
    		holder.playerLegs.setText(Integer.toString(mp.getNumLegs()));
    		if (match.getNumSets()>0) {
    			holder.playerSets.setText(Integer.toString(mp.getNumSets()));
    		}
    		holder.playerNumDarts.setText(Integer.toString(vs.getNumDartsThrown()));
        	if (themeId == R.style.Theme_BBC) {
	    		if (match.isLegStartPlayer(vs.getMatchPlayer())) {
	    			holder.playerMarkerAlt.setBackgroundColor(Color.parseColor("#FFFF00"));
	    		} else {
	    			holder.playerMarkerAlt.setBackgroundColor(0x00000000);
	    		}
        		
        	} else if (themeId == R.style.Theme_SKY ) {
	    		if (match.isCurrentPlayer(vs.getMatchPlayer())) {
	    			Drawable img = triangleDrawable(20 * (isLandscape ? 2 : 1),Color.BLACK);
	    			holder.playerMarker.setCompoundDrawablesWithIntrinsicBounds(img,null,null,null);
	    			holder.playerMarker.setBackgroundColor(0xFFFFFFFF);
	    		} else {
	        		holder.playerMarker.setText("");
	    			holder.playerMarker.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);    			
	    			holder.playerMarker.setBackgroundColor(0x00000000);
	    		}
	    		if (vs.get9Dart()) {
	    			holder.player9Dart.setText("9");
	    			holder.player9Dart.setBackgroundResource(R.drawable.yellow_ninedart_sky); 
	    		} else {
	    			holder.player9Dart.setText("");
	    			holder.player9Dart.setBackgroundColor(0x00000000);    			
	    		}
        	} else if (themeId == R.style.Theme_SKYWC2012 ) {
	    		if (match.isCurrentPlayer(vs.getMatchPlayer())) {
	    			Drawable img = triangleDrawable(20 * (isLandscape ? 2 : 1),Color.WHITE);
	    			holder.playerMarker.setCompoundDrawablesWithIntrinsicBounds(img,null,null,null);
	    		    holder.playerMarker.setBackgroundResource(R.drawable.green_background_right_sky);
	    		    //for some reason setBackgroundResource removes the padding attributes of the playerMarker
	    		    holder.playerMarker.setPadding((int)(4 * dpiScale * (isLandscape ? 2 : 1)), 0, 0, 0);
	    		} else {
	        		holder.playerMarker.setText("");
	    			holder.playerMarker.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);    			
	    			holder.playerMarker.setBackgroundColor(0x00000000);
	    		}
	    		if (vs.get9Dart()) {
	    			holder.player9Dart.setText("9");
	    			holder.player9Dart.setBackgroundResource(R.drawable.yellow_ninedart_sky); 
	    		} else {
	    			holder.player9Dart.setText("");
	    			holder.player9Dart.setBackgroundColor(0x00000000);    			
	    		}
        	}
    		String playerInfo= getPlayerInfoString(vs,position);
    		if (playerInfo != null) {	    			
    			holder.playerInfoString.setText(Html.fromHtml(playerInfo));    			
        		if (dpiScale > 1.5) {
        			holder.playerInfoString.setHeight(34 * (isLandscape ? 2 : 1));
        		} else {
        			holder.playerInfoString.setHeight(30 * (isLandscape ? 2 : 1));
        		}
    		} else {
    			holder.playerInfoString.setText("");
    			holder.playerInfoString.setHeight(0);
    			holder.playerInfoStringSpacer1.setHeight(0);
    			holder.playerInfoStringSpacer2.setHeight(0);
    		}
    		return view;
    	}
    	@Override
    	public boolean areAllItemsEnabled() {
            return false;
        }

    	@Override
        public boolean isEnabled(int position) {
            return false;
        }
    	
    }
	
	private String getPlayerInfoString(VisitScore vs, int playerInd) {
		//checkouts
		String str= null;
		String[] checkout= vs.getCheckout();
		if (checkout != null && checkout.length > 0) {
			str= checkout[0];
			if (checkout.length >= 2) {
				str= str+", "+checkout[1];
			}
			if (checkout.length >= 3) {
				str= str+", "+checkout[2];
			}
        	if (themeId == R.style.Theme_BBC) {
        		str= "<font color=\"#ffff00\">"+context.getString(R.string.scorematrix_checkout)+" </font>"+str;
        	}
		}
		
		//averages and other info to occasionally display
		if (str == null && showAverages) {
        	if (themeId == R.style.Theme_BBC) {
        		str= "<font color=\"#ffff00\">"+context.getString(R.string.scorematrix_three_dart_average)+" </font>"+String.format("%.02f",match.getPlayerStats().get(playerInd).getAverage()*3.0f);
        	} else if (themeId == R.style.Theme_SKY  || themeId == R.style.Theme_SKYWC2012) {
        		str= context.getString(R.string.scorematrix_three_dart_average)+" "+String.format("%.02f",match.getPlayerStats().get(playerInd).getAverage()*3.0f);
        	}
		}
		return str;
	}
	
	private void setDisplayVars() {
		Random generator = new Random();
		showAverages= generator.nextDouble() > 0.95;
	}
	
	private ShapeDrawable triangleDrawable(int size, int color) {

		    Point point1_draw = new Point(size,0);        
		    Point point2_draw = new Point(0,size/2);    
		    Point point3_draw = new Point(size,size);

		    Path path = new Path();
		    path.setFillType(Path.FillType.EVEN_ODD);
		    path.moveTo(point1_draw.x,point1_draw.y);
		    path.lineTo(point2_draw.x,point2_draw.y);
		    path.lineTo(point3_draw.x,point3_draw.y);
		    path.lineTo(point1_draw.x,point1_draw.y);
		    path.close();

		    ShapeDrawable pathShape= new ShapeDrawable(new PathShape(path,size,size));
		    pathShape.setIntrinsicWidth(size);
		    pathShape.setIntrinsicHeight(size);
		    Paint paint= pathShape.getPaint();
		    paint.setColor(color);     
		    paint.setStyle(Paint.Style.FILL);
		    paint.setAntiAlias(true);

		    return pathShape;
		    //canvas.drawLine(point1_draw.x,point1_draw.y,point2_draw.x,point2_draw.y, paint);
	}
	        
}
